package com.zhuiyi.yiqingbackend.service.impl;

import com.zhuiyi.yiqingbackend.common.ErrorCode;
import com.zhuiyi.yiqingbackend.domain.Base;
import com.zhuiyi.yiqingbackend.domain.Car;
import com.zhuiyi.yiqingbackend.exception.BusinessException;
import com.zhuiyi.yiqingbackend.mapper.CarMapper;
import com.zhuiyi.yiqingbackend.service.BaseService;
import com.zhuiyi.yiqingbackend.service.CarService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
@Service
public class CarServiceImpl implements CarService {

    @Resource
    private CarMapper carMapper;
    @Resource
    private BaseService baseService;
    @Override
    public List<Car> getAllCar() {
        return carMapper.getAllCar();
    }

    @Override
    public boolean insertCar(Car car) {
        String idcar = car.getIdcar();
        if(StringUtils.isBlank(idcar) || StringUtils.isEmpty(idcar)){
            throw new BusinessException(ErrorCode.PARAM_ERROR,"车牌号为必填项");
        }
        String phone = car.getPhone();
//        if(phone == null || phone.equals("")){
//            throw new BusinessException(ErrorCode.NULL_ERROE, "手机号不能为空");
//        }
        Base base = baseService.getBaseByPhone(phone);
        if(base!=null){
            int baseId = base.getId();
            car.setBaseid(baseId);
            boolean result = carMapper.insertCar(car);
            return result;
        }else{
            return carMapper.insertCar(car);
        }

    }

    @Override
    public boolean deleteCar(int id) {
        Car car = carMapper.getCarById(id);
        if(car == null){
            throw new BusinessException(ErrorCode.FAIL,"删除失败");
        }
        boolean result = carMapper.deleteCar(id);

        if(!result){
            throw new BusinessException(ErrorCode.FAIL,"删除失败");
        }

        return result;
    }

    @Override
    public boolean updateCar(Car car) {
        Car car1 = carMapper.getCarById(car.getId());
        if(car1 == null){
            throw new BusinessException(ErrorCode.FAIL,"修改失败");
        }
        boolean result = carMapper.updateCar(car);
        if(!result){
            throw new BusinessException(ErrorCode.FAIL,"修改失败");
        }
        return result;
    }

    @Override
    public Car getCarById(int id) {
        Car car = carMapper.getCarById(id);
        if(car == null){
            throw new BusinessException(ErrorCode.FAIL,"查询失败,没有该车辆");
        }
        return car;
    }

    @Override
    public Car getCarByBaseId(int baseid) {
        Car car = carMapper.getCarByBaseId(baseid);
//        患者可以没有车，但不能没有基本信息
//        if(car == null){
//            throw new BusinessException(ErrorCode.FAIL,"查询失败,没有该车辆");
//        }
        return car;
    }
}
